<template>
  <div class="modal">
    <el-dialog v-model="modalState" :title="modalTitle" width="30%" center>
      <div class="form">
        <el-form
          :model="formData"
          label-width="100px"
          label-position="left"
          size="large"
          ref="ruleFormRef"
          :rules="rules"
          status-icon
        >
          <el-form-item label="用户名" prop="name">
            <el-input placeholder="请输入用户名" v-model="formData.name" />
          </el-form-item>

          <el-form-item label="真实姓名" prop="realname">
            <el-input placeholder="请输入真实姓名" v-model="formData.realname" />
          </el-form-item>

          <template v-if="isNewRef">
            <el-form-item label="密码" prop="password">
              <el-input placeholder="请输入用户密码" v-model="formData.password" show-password />
            </el-form-item>
          </template>

          <el-form-item label="手机号码" prop="cellphone">
            <el-input placeholder="请输入手机号码" v-model="formData.cellphone" />
          </el-form-item>

          <el-form-item label="角色" prop="roleId">
            <el-select placeholder="请选择角色" v-model="formData.roleId" style="width: 100%">
              <template v-for="item in mainStore.entireRole">
                <el-option :label="item.name" :value="item.id"></el-option>
              </template>
            </el-select>
          </el-form-item>

          <el-form-item label="部门" prop="departmentId">
            <el-select placeholder="请选择部门" v-model="formData.departmentId" style="width: 100%">
              <template v-for="item in mainStore.entireDepartment">
                <el-option :label="item.name" :value="item.id"></el-option>
              </template>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="btns">
          <el-button type="primary" @click="handleConfirmClick">提交</el-button>
          <el-button @click="modalState = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, defineExpose, reactive } from 'vue'
import { ElMessage } from 'element-plus'

import useStytem from '@/store/main/system/system'
import useMainStore from '@/store/main/main'

import type { FormRules, FormInstance } from 'element-plus'

const mainStore = useMainStore()
const systemStore = useStytem()
const modalState = ref(false)
const ruleFormRef = ref<FormInstance>()
const formData = reactive({
  name: '',
  realname: '',
  password: '',
  cellphone: '',
  roleId: '',
  departmentId: ''
})
// 判断是否是点击新建按钮弹出弹窗
const isNewRef = ref()
const modalTitle = ref('')
const editData = ref()
// 表单校验规则
const rules: FormRules = {
  name: [
    { required: true, message: '请输入', trigger: 'blur' },
    {
      message: '必须由4~20位数字或字母组成',
      trigger: 'blur',
      pattern: /^[a-z0-9]{4,20}$/
    }
  ],
  password: [
    { required: true, message: '请输入', trigger: 'blur' },
    {
      min: 4,
      message: '密码长度至少为4位',
      trigger: 'blur'
    },
    {
      message: '密码必须包含大小写字母和数字的组合',
      trigger: 'blur',
      pattern: /^[a-z0-9A-Z]{4,}$/
    }
  ],
  realname: [
    { required: true, message: '请输入', trigger: 'blur' },
    {
      message: '请输入2位以上的汉字',
      trigger: 'blur',
      pattern: /^[\u4e00-\u9fa5]{0,}$/
    }
  ],
  cellphone: [
    { required: true, message: '请输入', trigger: 'blur' },
    {
      message: '请输入正确格式的手机号码',
      trigger: 'blur',
      pattern: /^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/
    }
  ]
}

function setModalState(isNew: boolean = true, itemData?: any) {
  modalState.value = true
  isNewRef.value = isNew
  editData.value = itemData
  if (!isNew && formData) {
    // 新建用户
    for (const key in formData) {
      formData[key] = itemData[key]
    }
  } else {
    // 修改用户
    for (const key in formData) {
      formData[key] = ''
    }
  }

  if (isNew) {
    modalTitle.value = '新建用户'
  } else {
    modalTitle.value = '修改用户'
  }
}

// 提交按钮的事件
function handleConfirmClick() {
  ruleFormRef.value.validate(async (value) => {
    if (value) {
      if (isNewRef.value) {
        // 新建用户
        systemStore.createUserAction(formData).then((res) => {
          if (res.code === 0) {
            ElMessage({
              message: '用户创建成功',
              type: 'success'
            })
          } else {
            ElMessage({
              message: '用户创建失败',
              type: 'error'
            })
          }
        })
      } else {
        // 修改用户
        systemStore.editUserAction(editData.value.id, formData).then((res) => {
          if (res.code === 0) {
            ElMessage({
              message: '用户修改成功',
              type: 'success'
            })
          } else {
            ElMessage({
              message: '用户修改失败',
              type: 'error'
            })
          }
        })
      }

      modalState.value = false
      ruleFormRef.value.resetFields()
    } else {
      ElMessage({
        message: '检验不通过,请重试',
        type: 'warning'
      })
    }
  })
}

defineExpose({ setModalState })
</script>

<style lang="scss" scoped>
.btns {
  display: flex;
  justify-content: flex-end;
}
</style>
